/*
 * @lc app=leetcode.cn id=63 lang=golang
 *
 * [63] 不同路径 II
 */

// 2. 动态规划
// @lc code=start
func uniquePathsWithObstacles(obstacleGrid [][]int) int {
	m := len(obstacleGrid)
	n := len(obstacleGrid[0])

	dp := make([][]int, m)
	flag := true
	for i := 0; i < m; i++ { // 第一行一旦有障碍物，则后面的都到不了
		dp[i] = make([]int, n)
		if flag && obstacleGrid[i][0] == 1 {
			flag = false
		}
		if flag {
			dp[i][0] = 1
		}

	}

	flag = true
	for i := 0; i < n; i++ { // 第一列一旦有障碍物，则后面的都到不了
		if flag && obstacleGrid[0][i] == 1 {
			flag = false
		}
		if flag {
			dp[0][i] = 1
		}
	}

	for i := 1; i < m; i++ {
		for j := 1; j < n; j++ {
			if obstacleGrid[i][j] == 1 {
				dp[i][j] = 0
			} else {
				dp[i][j] = dp[i-1][j] + dp[i][j-1]
			}
		}
	}
	return dp[m-1][n-1]
}

// @lc code=end

// 1. 直接深度优先 超时 30/41
// @lc code=start
func uniquePathsWithObstacles(obstacleGrid [][]int) (ans int) {
	m := len(obstacleGrid)
	n := len(obstacleGrid[0])
	var dfs func(x, y int)
	dfs = func(x, y int) {
		if x > m-1 || y > n-1 || obstacleGrid[x][y] == 1 {
			return
		}

		if x == m-1 && y == n-1 {
			ans += 1
		}
		dfs(x+1, y)
		dfs(x, y+1)
	}

	dfs(0, 0)
	return
}

// @lc code=end

